package com.ybl.store.common.web;

import com.ybl.store.common.convention.exception.AbstractException;
import com.ybl.store.common.convention.result.Result;
import com.ybl.store.common.convention.result.Results;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常拦截器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义 {@link AbstractException} 异常拦截器
     */
    @ExceptionHandler(AbstractException.class)
    public Result<Void> abstractException(HttpServletRequest request, AbstractException ex) {
        log.error("[{}] {} [ex] {}", request.getMethod(), request.getRequestURL().toString(), ex.toString());
        return Results.failure(ex);
    }

    /**
     * 默认异常拦截器
     */
    @ExceptionHandler(Throwable.class)
    public Result<Void> defaultExceptionHandler(HttpServletRequest request, Throwable ex) {
        log.error("[{}] {}", request.getMethod(), request.getRequestURL().toString(), ex);
        return Results.failure();
    }
}
